package com.cxm.qyyz.ui.setting;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;

import com.cxm.qyyz.R;
import com.cxm.qyyz.base.activity.BaseActivity;
import com.cxm.qyyz.presenter.MainPresenter;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

public class WebViewActivity extends BaseActivity<MainPresenter> {

    private static final String[] permissions = {Manifest.permission.CAMERA};

    /**
     * 拍照/选择文件请求码
     */
    private static final int REQ_CAMERA = 1;
    private static final int OPEN_CAMERA = 100;
    private static final int REQ_CHOOSE = REQ_CAMERA + 1;

    private final static int VIDEO_REQUEST = 120;
    private WebView mWebView;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadMessageArray;

    private static final String PATH = Environment
            .getExternalStorageDirectory() + "/DCIM";
    private String imageName;


    @Override
    protected void initInjector() {

    }

    @Override
    protected int getLayoutId() {
        return 0;
    }

    @Override
    public String getTitles() {
        return getIntent().getStringExtra("title");
    }

    @Override
    protected void initEvents() {
        initViews();
        initWebviews();
    }

    private void initWebviews() {
        mWebView.setWebChromeClient(new WebChromeClient() {
            // For Android >=3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                if (acceptType.equals("image/*")) {
                    if (mUploadMessage != null) {
                        mUploadMessage.onReceiveValue(null);
                        return;
                    }
                    mUploadMessage = uploadMsg;
                    selectImage();
                } else {
                    onReceiveValue();
                }
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooser(uploadMsg, "image/*");
            }

            // For Android  >= 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooser(uploadMsg, acceptType);
            }

            // For Android  >= 5.0
            @Override
            @SuppressLint("NewApi")
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
                        && fileChooserParams.getAcceptTypes().length > 0 && fileChooserParams.getAcceptTypes()[0].equals("image/*")) {
                    if (mUploadMessageArray != null) {
                        mUploadMessageArray.onReceiveValue(null);
                    }
                    mUploadMessageArray = filePathCallback;
                    selectImage();
                } else if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
                        && fileChooserParams.getAcceptTypes().length > 0 && fileChooserParams.getAcceptTypes()[0].equals("video/*")) {
                    if (mUploadMessageArray != null) {
                        mUploadMessageArray.onReceiveValue(null);
                    }
                    mUploadMessageArray = filePathCallback;
                    recordVideo();
                } else if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
                        && fileChooserParams.getAcceptTypes().length > 0 && fileChooserParams.getAcceptTypes()[0].equals("*/*")) {
                    if (mUploadMessageArray != null) {
                        mUploadMessageArray.onReceiveValue(null);
                    }
                    mUploadMessageArray = filePathCallback;
                    openFileInput();
                } else {
                    onReceiveValue();
                }
                return true;
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
                                      @Override
                                      public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                          mWebView.loadUrl(url);
                                          return true;
                                      }
                                  }
        );
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        loadUrl();
    }


    private void openFileInput() {
        imageName = String.valueOf(System.currentTimeMillis());
        String picturePath = PATH;
        File file = new File(picturePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri output = Uri.fromFile(file);
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, output);

        Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("*/*");

        Intent chooserIntent = Intent.createChooser(galleryIntent, "选择操作");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
        startActivityForResult(chooserIntent, REQ_CHOOSE);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }
    /**
     * 录像
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        //限制时长
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
        //开启摄像机
        startActivityForResult(intent, VIDEO_REQUEST);
    }

    private void selectImage() {
        String[] selectPicTypeStr = {"拍摄", "从相册中选择"};
        new AlertDialog.Builder(this)
                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        onReceiveValue();
                    }
                })
                .setItems(selectPicTypeStr, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        switch (which) {
                            // 相机拍摄，此处调用系统相机拍摄图片，开发者可根据实际情况选用系统相机还是自己在这之上封装一层从而符合APP风格
                            case 0:
                                checkPermission();

                                break;
                            // 手机相册，此处调用系统相册选择图片，开发者可根据实际情况选用系统相册还是自己在这之上封装一层从而符合APP风格
                            case 1:
                                openAlbum();
                                break;
                            default:
                                break;
                        }

                    }
                })
                .show();
    }

    private void openAlbum() {
        if (!hasSDcard()) {
            return;
        } else {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_PICK);
            intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//使用以上这种模式，并添加以上两句
            startActivityForResult(intent, REQ_CHOOSE);
        }
    }

    private void openCamera() {



        if (!hasSDcard()) {
            return;
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imageName = System.currentTimeMillis() + ".png";
            File file = new File(PATH);
            if (!file.exists()) {
                file.mkdirs();
            }

            Uri photoUri = FileProvider.getUriForFile(
                    this,
                    getPackageName() + ".fileprovider",
                    new File(PATH, imageName));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(intent, REQ_CAMERA);
        }
    }

    private boolean hasSDcard() {
        boolean flag = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (!flag) {
            Toast.makeText(this, "请插入手机存储卡再使用本功能", Toast.LENGTH_SHORT).show();
            onReceiveValue();
        }
        return flag;
    }

    private void loadUrl() {
//        mWebView.loadUrl("https://qiyukf.com/client?k=ba5e6e832ae0cf651df1540eaabc62eb&wp=1");
        mWebView.loadUrl(getIntent().getStringExtra("url"));
    }

    private void initViews() {

    }


    private void checkPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            openCamera();
        } else {
            EasyPermissions.requestPermissions(
                    new PermissionRequest.Builder(this, OPEN_CAMERA, permissions)
                            .setTheme(R.style.PermissionTheme)
                            .setRationale(R.string.text_permisson_xi)
                            .setPositiveButtonText(R.string.text_permissions_apply)
                            .setNegativeButtonText(R.string.text_permissions_cancel)
                            .build());
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @androidx.annotation.NonNull List<String> perms) {
        if (requestCode != OPEN_CAMERA) {
            return;
        }
        List<String> data = Arrays.asList(permissions);
        if (perms.containsAll(data)) {
            openCamera();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @androidx.annotation.NonNull List<String> perms) {
        if (requestCode != OPEN_CAMERA) {
            return;
        }
        if (EasyPermissions.somePermissionDenied(this, permissions) || EasyPermissions.somePermissionPermanentlyDenied(this, Arrays.asList(permissions))) {
            new AppSettingsDialog.Builder(this)
                    .setThemeResId(R.style.PermissionTheme)
                    .setTitle(R.string.text_permissions_preference)
                    .setRationale(R.string.text_permissions_setting)
                    .setPositiveButton(R.string.text_permissions_apply)
                    .setNegativeButton(R.string.text_permissions_cancel)
                    .setRequestCode(OPEN_CAMERA)
                    .build()
                    .show();
        }
    }





    /**
     * 返回文件选择
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode != RESULT_OK) {
            onReceiveValue();
            return;
        }
        switch (requestCode) {
            case OPEN_CAMERA:
                if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
                    openCamera();
                }
                break;
            case REQ_CAMERA:
                File fileCamera = new File(PATH, imageName);
                handleFile(fileCamera);
                break;
            case REQ_CHOOSE:
//                Uri uri = intent.getData();
//                String absolutePath = PathUtils.getPath(this, uri);
//                File fileAlbum = new File(absolutePath);
//                handleFile(fileAlbum);
                break;
            case VIDEO_REQUEST:
                if (null == mUploadMessage && null == mUploadMessageArray) return;

                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                if (mUploadMessageArray != null) {
                    if (resultCode == RESULT_OK) {
                        mUploadMessageArray.onReceiveValue(new Uri[]{result});
                        mUploadMessageArray = null;
                    } else {
                        mUploadMessageArray.onReceiveValue(new Uri[]{});
                        mUploadMessageArray = null;
                    }

                } else if (mUploadMessage != null) {
                    if (resultCode == RESULT_OK) {
                        mUploadMessage.onReceiveValue(result);
                        mUploadMessage = null;
                    } else {
                        mUploadMessage.onReceiveValue(Uri.EMPTY);
                        mUploadMessage = null;
                    }

                }

        }
    }

    private void handleFile(File file) {
        if (file.isFile()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (null == mUploadMessageArray) {
                    return;
                }
                Uri uri = Uri.fromFile(file);
                Uri[] uriArray = new Uri[]{uri};
                mUploadMessageArray.onReceiveValue(uriArray);
                mUploadMessageArray = null;
            } else {
                if (null == mUploadMessage) {
                    return;
                }
                Uri uri = Uri.fromFile(file);
                mUploadMessage.onReceiveValue(uri);
                mUploadMessage = null;
            }
        } else {
            onReceiveValue();
        }

    }

//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
//            mWebView.goBack();
//            return true;
//        } else {
//            finish();
//        }
//        return super.onKeyDown(keyCode, event);
//    }


    private void onReceiveValue() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mUploadMessageArray != null) {
                mUploadMessageArray.onReceiveValue(null);
                mUploadMessageArray = null;
            }
        } else {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
        }
    }
}
